"use strict";
const Service = require("egg").Service;
const { httpCode } = require("../../utils/userConfig");
const SystemErrException = require("../../exception/systemError");
const LogicErrException = require("../../exception/logicError");
const await = require("await-stream-ready/lib/await");
const { Op } = require("sequelize");
const { v4: uuidv4 } = require('uuid');

class DepartmentMgmtService extends Service {

  async add(department) {
    try {
      const { ctx } = this;
      delete department.unitName;
      await ctx.model.Organization.Departments.create(department);
      return {
        code: httpCode.SUCCESS,
        message: "新增部门成功"
      }
    } catch (error) {
      throw new SystemErrException("部门添加异常：" + error);
    }
  }

  async list(query) {
    try {
      const { ctx, app } = this;
      let { unitId } = query;
      let searchCondition = {};
      if (unitId) {
        searchCondition.unitId = unitId;
      }
      let departments = await ctx.model.Organization.Departments.findAll({
        where: searchCondition,
        include: {
          model: ctx.model.Organization.Units
        },
        order: [['create_date', 'desc']],
      });
      departments = JSON.parse(JSON.stringify(departments));
      departments.forEach(department => {
        department.unitName = department.OUnit.name;
        department.allName = `${department.unitName}-${department.name}`
        delete department.Unit;
      });
      let count = await ctx.model.Organization.Departments.count();
      return {
        data: {
          data: departments,
          count
        },
        code: httpCode.SUCCESS,
        message: '部门列表查询成功！'
      }
    } catch (error) {
      throw new SystemErrException("部门列表查询异常：" + error);
    }
  }


  async getDepartmentById(id) {
    try {
      const { ctx, app } = this;
      const department = await ctx.model.Organization.Departments.findByPk(id);
      return {
        data: department,
        code: httpCode.SUCCESS,
        message: '获取部门信息成功!'
      }
    } catch (error) {
      throw new SystemErrException("获取部门信息异常：" + error);
    }
  }

  async update(department) {
    try {
      const { id, name, remark, unitId } = department;
      await this.ctx.model.Organization.Departments.update(
        {
          name, remark, unitId
        },
        {
          where: { id },
        }
      );
      return {
        code: httpCode.SUCCESS,
        message: "部门信息更新成功！",
      };
    } catch (error) {
      throw new SystemErrException("部门信息更新异常：" + error);
    }
  }

  async delete({ id }) {
    try {
      const { ctx } = this;
      await ctx.model.Organization.Departments.destroy({
        where: { id }
      });
      return {
        code: httpCode.SUCCESS,
        message: "单位信息删除成功！"
      }
    } catch (error) {
      throw new SystemErrException("单位信息删除异常：" + error);
    }
  }

}

module.exports = DepartmentMgmtService;
